<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="用户ID" prop="uid">
        <el-input v-model="queryParams.uid" placeholder="请输入用户ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="日期" prop="dateInfo">
        <el-date-picker clearable v-model="queryParams.dateInfo" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择日期" :default-value="getDefaultDate()">
        </el-date-picker>
      </el-form-item>
<!--      <el-form-item label="渠道名称" prop="channelName" class="single-line-label">-->
<!--        <span class="label-spacing"></span>-->
<!--        <el-select v-model="queryParams.channelName" clearable placeholder="请选择渠道名称" filterable default-first-option-->
<!--          allow-create @change="handleStatusChange">-->
<!--          <el-option v-for="(item, i) in extData.channelNameList || []" :key="i" :label="item.key"-->
<!--            :value="item.value"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="渠道名称" prop="channelCode" class="single-line-label">
        <span class="label-spacing"></span>
        <el-select  v-model="queryParams.channelCode"  clearable placeholder="请选择渠道名称" filterable
                    @keyup.enter.native="handleQuery">
          <el-option v-for="(item, i) in extData.channelNameList || []" :key="i" :label="item.key"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单价" prop="priceAmount">
        <el-input v-model="queryParams.priceAmount" placeholder="请输入单价" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable filterable allow-create
          default-first-option @change="handleStatusChange">
          <el-option label="进件成功" value="SUCCESS"></el-option>
          <el-option label="进件失败" value="FAILED"></el-option>
          <el-option label="INIT" value="INIT"></el-option>
          <el-option label="撞库失败" value="MATCH_FAILED"></el-option>
          <el-option label="等待推送-半" value="WAIT_APPROVE"></el-option>
          <el-option label="等待推送-全" value="WAIT_PUSH"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="pushManual"
          v-hasPermi="['merchant:baseInfo:pushManual']">推送</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="pushInfoList">
      <el-table-column label="用户ID" align="center" prop="uid" fixed-width="200">
        <template slot-scope="scope">
          <span class="clickable-uid" @click="handleDetailsDialog(scope.row)">{{ scope.row.uid }}</span>
        </template>
      </el-table-column>
      <el-table-column label="日期" align="center" prop="dateInfo" />
      <el-table-column label="价格" align="center" prop="priceAmount" />
      <el-table-column label="渠道名称" align="center" prop="realname" width="200">
        <template slot-scope="scope">
          {{ scope.row.channelCode }} | {{ scope.row.channelName }}
        </template>
      </el-table-column>
      <el-table-column label="用户姓名" align="center" prop="realname">
        <template slot-scope="scope">
          {{ scope.row.realname }} | {{ scope.row.mobile }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="手机号" align="center" prop="mobile" /> -->
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="推送结果" align="center" prop="code">
        <template slot-scope="scope">
          {{ scope.row.code }} | {{ scope.row.message }} | {{ scope.row.queryStatus }}
        </template>
      </el-table-column>
      <el-table-column label="客户星级" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.startLevel === -1">未上传</span>
          <span v-else>{{ scope.row.startLevel }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="返回信息" align="center" prop="message" /> -->
      <el-table-column label="创建时间" align="center" width="135">
        <template slot-scope="scope">
          {{ formatTimestamp(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" type="text" icon="el-icon-info" @click="handleUpdate(scope.row)"
            v-hasPermi="['merchant:pushInfo:edit']">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商户推送信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="返回码" prop="code">
          <el-input v-model="form.code" :readonly="true" />
        </el-form-item>
        <el-form-item label="返回信息" prop="message">
          <el-input v-model="form.message" :readonly="true" />
        </el-form-item>
        <el-form-item label="返回数据" prop="result">
          <el-input v-model="form.result" :readonly="true" />
        </el-form-item>
        <!-- <el-form-item label="授权地址" prop="approveUrl">
          <el-input v-model="form.approveUrl" type="textarea" :readonly="true" />
        </el-form-item> -->
        <el-form-item label="查询结果" prop="queryStatus">
          <el-input v-model="form.queryStatus" type="textarea" :readonly="true" />
        </el-form-item>
        <el-form-item label="查询信息" prop="queryResultInfo">
          <el-input v-model="form.queryResultInfo" type="textarea" :readonly="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 用户详情弹窗 -->
    <Member ref="MemberRef" />

  </div>
</template>

<style scoped>
.clickable-uid {
  cursor: pointer;
  color: blue;
}

.clickable-uid:hover {
  text-decoration: underline;
}
</style>

<script>
import { listPushInfo, getPushInfo, delPushInfo, addPushInfo, updatePushInfo } from "@/api/merchant/pushInfo";
import { baseInfoExtData } from "@/api/source/baseInfo";
import Member from '@/views/member/memeber.vue'
export default {
  name: "PushInfo",
  components: {
    Member
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商户推送信息表格数据
      pushInfoList: [],
      selectedChannelNames: [],
      // 弹出层标题
      title: "",
      extData: {},
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        priceAmount: null,
        uid: null,
        infoId: null,
        dateInfo: this.getDefaultDate(),
        channelName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }, 
      infoId: "",
      uid: "",
    };
  },
  created() {
    this.getOptions();
    this.infoId = this.$route.query.infoId
    this.uid = this.$route.query.uid
    this.queryParams.uid = this.$route.query.uid;
    this.getList();
  },
  watch: {
    '$route'(to, from) {
      // 当路由参数变化时执行相应操作
      if (to.query.uid !== from.query.uid) {
        this.queryParams.uid = this.$route.query.uid;
        this.getList() // 重新加载数据
      }
    }
  },
  methods: {
    getOptions() {
      baseInfoExtData().then((response) => {
        this.extData = response.data;
      });
    },
    pushManual() {
      // 跳转手动推送
      const tempInfoId = this.infoId || this.$route.query.infoId
      this.$router.push({ path: '/merchant/pushManual', query: { infoId: tempInfoId } })
    },
    /**用户uid跳转 */
    async handleDetailsDialog(row) {
      this.$refs.MemberRef.show(row.uid)
    },
    handleStatusChange(value) {
      console.log("Selected status:", value);
    },
    /** 查询商户推送信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.infoId = this.$route.query.infoId;
      
      if (this.$route.query.status) {
        this.queryParams.status = this.$route.query.status;
      }

      if (this.$route.query.channelName) {
        this.queryParams.channelName = this.$route.query.channelName ;
      }

      // 检查是否明确设置了dateInfo
      if (typeof this.queryParams.dateInfo === 'undefined' || this.queryParams.dateInfo === null) {
        this.queryParams.dateInfo = '';
      }

      console.log('Fetching list with params:', this.queryParams); // 添加日志
      listPushInfo(this.queryParams).then(response => {
        this.pushInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    }
    ,
    getDefaultDate() {
      // 获取当天日期，并以 yyyy-MM-dd 格式返回
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    /**更改创建时间格式 */
    formatTimestamp(timestamp) {
      if (!timestamp) {
        return '';
      }
      const date = new Date(timestamp);
      const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      return formattedDate;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        uid: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.uid = '';
      this.queryParams.dateInfo = ''; // 或者设置为 null
      this.queryParams.channelName = '';
      this.handleQuery();
    }
    ,
    /** 查看按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPushInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看其他信息";
      });
    },
  }
};
</script>
